import { ElMessage } from 'element-plus';
import axios from 'axios';
import store from '@/store';
import router from '@/router';
import useUser from '@/hooks/useUser';

let requestError = false; // 解决多次401导致的router问题
const baseURL = import.meta.env.PROD ? import.meta.env.VITE_APP_API_HOST : '';

const service = axios.create({
  baseURL,
  // baseURL: 'https://mock.startdt.net/mock/555',
  timeout: 10000,
  // withCredentials: true,
});

const getAuth = () => {
  const [user] = useUser();
  const auth = user.value ? user.value.token : '';
  return auth;
};

function request({ url, data = {}, method = 'get', showMsg = true, noAuth = false, formData = false, config = {} }) {
  method = method.toLowerCase();
  if (method === 'get' || method === 'delete') {
    data = {
      params: {
        ...data,
      },
    };
  } else {
    data = {
      data: {
        ...data,
      },
    };
  }

  if (!noAuth) {
    config.headers = {
      Authorization: getAuth(),
    };
    if (formData) {
      config.headers['Content-Type'] = 'multipart/form-data';
    }
  }

  return service({ method, url, ...data, ...config }).then((result) => {
    const res = result.data || {};
    const { code } = res;
    // token过期
    if (code === 401 || code === 403) {
      localStorage.clear();
      if (!requestError) {
        router.push({
          path: '/login',
          query: {
            to: router.currentRoute.path,
          },
        });
      }
      requestError = true;
    }
    if (code === 200) {
      requestError = false;
      return res.data;
    }
    if (showMsg) {
      ElMessage.closeAll();
      ElMessage.error(res.msg || JSON.stringify(res.code));
    }
    return Promise.reject(res);
  }).catch((error) => {
    if (error.msg || error) {
      ElMessage.closeAll();
      ElMessage.error(error.msg || error);
    }
    return Promise.reject(error);
  });
}

export default request;

export function exportPostElx(url, data, fileName = '表格.xls') {
  const auth = store.state.common.token;
  const options = {
    responseType: 'blob',
    headers: {
      Authorization: auth,
    },
  };
  const api = url.startsWith('http') ? url : baseURL + url;
  return axios.post(api, data, options).then((res) => {
    const { data: bData } = res;
    const blob = new Blob([bData]);
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a');
      elink.download = fileName;
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName);
    }
  });
}
